<?php
namespace app\ausagent\controller;
use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use think\Loader;
use Memcached;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\MemcachedCache;
use EasyWeChat\Payment\Order;
use Qcloud\cos\Api;
class Initialization extends controller{

	public function _initialize(){
		if(!session('nickname')){
          // $this->error('您尚未登录系统',url('login/index')); 
          $this->redirect(\think\Request::instance()->root().'/ausagent/Login/index');
        }
	}
	private function initialize()
    {
        //判断是否为子商户

            $options = [
                'app_id' => config('wechat.APPID'),
                'secret'  =>config('wechat.APPSECRET'),    
                'payment' => [
                    'merchant_id'        => config('wechat.MCHID'),
                    'key'                => config('wechat.KEY'),
                    'cert_path'          => config('wechat.SSLCERT_PATH'),
                    'key_path'           => config('wechat.SSLKEY_PATH'),
                    'notify_url'         => config('website').'/ausagent/Initialization/rechargenotify',
                    'sub_app_id'      => 'wx22efd1659c0af5f0',
                    'sub_merchant_id' => '1480237892',
                ],
                'log' => [
                    'level' => 'debug',
                    'file'  => '../log/easywechat.log',
                ],
            ];
        	if(config('wechatchche')){
	            $memcached = new Memcached();
	            $memcached->addServer(config('wechatchche.host'), config('wechatchche.port'));
	            $cacheDriver = new MemcachedCache();
	            $cacheDriver->setMemcached($memcached);
	            $options['cache']=$cacheDriver;
	        }
        $app = new Application($options);
        return $app;
    }

	public function index(){

		//查询基本信息
		$baseinfo = Db::name('operator')->where(['id'=>session('oid'),'is_delete'=>1])->find();
		$this ->assign('v',$baseinfo);
		//订单查询
		$orders = Db::name('operator_order')->where(['oid'=>session('oid'),'is_delete'=>1])->order('create_time desc')->find();
		if($orders){
			$this->assign('dd',$orders);
			if($orders['pay_status']==0){
				$orderno = $orders['order_no'];//订单号
				$detail = '曼联智能柜软件服务费用';
				$price = $orders['real_amount'];
				$notify_url = config('website').'/ausagent/Initialization/rechargenotify';
				$app = $this ->initialize();
	        	$payment = $app->payment;
	        	$attributes = [
		            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
		            'body'             => $detail,  //订单名称
		            'detail'           => $detail,  //订单描述
		            'out_trade_no'     => $orderno,  //订单号
		            'total_fee'        => $price*100, // 单位：分
		            'notify_url'       => $notify_url,
	        	];
	        	$order = new Order($attributes);
	        	$result = $payment->prepare($order);//var_dump($result);die;
	        	if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
	        		$prepayId = $result->prepay_id;
		            $url = $result->code_url;
		            $errorCorrectionLevel ='L';//容错级别
			        $matrixPointSize = intval(18);//生成图片大小
			        Loader::import('qrcode.phpqrcode');
			        //生成二维码图片
			        \QRcode::png($url, 'payqrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
			        $QR = 'payqrcode.png';//已经生成的原始二维码图 
			        //$QR = imagecreatefromstring(file_get_contents($QR)); //打开文件
			        //输出图片 
			        //Header("Content-type: image/png");
			        //ImagePng($QR,'payqrcode.png');
			        $imgurl ='/payqrcode.png';
			        $this->assign('img',$imgurl);
	        	}else{
	                $res['code']= -1050;
	                $res['info']= $result;
	                return $res;
	            }
			}
		}

		//$this->assign('oider',$order);
		//验证短信接口是否已设置
		$sms = Db::name('verificationcode')->where(['oid'=>session('oid')])->find();
		if($sms){
			$this->assign('sms',$sms);
		}
		//支付接口是否已设置
		$pay = Db::name('wechatpay')->where('oid',session('oid'))->find();
		if($pay){
			$this->assign('pay',$pay);
		}
		//协议内容是否已设置
		$xy = Db::name('agreement')->where('oid',session('oid'))->find();
		if($xy){
			$this->assign('xy',$xy);
		}
		return view();
	}

	public function base(){
		if ( Request::instance()->isPost() ) {
			$data = input('post.');
			if($_FILES['logo']['name']){
				$file = Request::instance()->file('logo');
				$info=$file->move(ROOT_PATH . 'public' . DS . 'uploads');
				$file = $info->getSaveName();
				if($file){
                    $cosApi = new Api(config('Qcloud'));
                    $bucket = config('Qcloud.bucket');
                    $src = ROOT_PATH . 'public/uploads/'.$file;
                    $dst = 'operator/logo/'. $file;
                    $ret = $cosApi->upload($bucket, $src, $dst);
					if($ret['code']==0){
	                    $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
	                    $len = strlen($bucket);  //计算bucketname长度
	                    $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
	                    $start +=$len;  
	                    $newpath = substr($path,$start);  //截取路径
	                    unlink($src);  //删除服务器上面的资源文件
	                    $res['code'] = '1';
	                    $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
	                    $res['url'] = $ret['data']['access_url'];   //资源文件URL
	                    $data['logo'] = $res['picture'];
	                    //return $res;
	                }   
                }
		        //$data['logo'] = '/uploads/'.$file;
			}
			$data['id'] = (int)input('id');
			if($data['name']=='' || $data['contacts']=='' || $data['mobile']=='' || $data['addrs']=='' || $data['servicephone']=='' || $data['deposit']=='' || $data['billingtime']=='' || $data['amount']=='' || $data['introduce']==''){
				return ['code'=>-1050, 'msg'=>'必填项不能有空值!'];
			}
			$check = Db::name('operator')->where(['name'=>$data['name'],'is_delete'=>1])->where('id','<>',$data['id'])->find();
			if($check){
				return ['code'=>-1050, 'msg'=>'运营商名称已存在!'];
			}
			
			$prepaidamount = input('post.prepaidamount/a',[]);
			$s2 = implode('|',$prepaidamount);
			$data['prepaidamount'] = $s2;
			//if(Db::name('operator')->update($data)){
			$result = Db::name('operator')->update($data);
			if($result !== false){	
				return ['code'=>0, 'msg'=>'更新成功!!'];
			}else{
				return ['code'=>-1050, 'msg'=>'录入信息有误请仔细检查!'];
			}

		}else{
			die('非法操作');
		}

	}

	public function sms(){
		if ( Request::instance()->isPost() ) {
			$data = input('post.');
			if($data['appid']=='' || $data['appkey']=='' || $data['templid']=='' || $data['signname']=='' || $data['codename']=='' || $data['timename']==''){
				return ['code'=>-1050, 'msg'=>'必填项不能有空值!'];
			}
			if($data['param']==''){
				return ['code'=>-1050, 'msg'=>'模版内容必须填写!'];
			}
			$id = (int)input('id');
			if(!$id){
				$data2 = Request::instance()->only('provider,types,time,appid,appkey,templid,signname,param,codename,timename','post');
				$data2['oid'] = session('oid');
				//var_dump($data2);die;
				$ret = Db::name('verificationcode')->insert($data2);
				if($ret){
					return ['code'=>0, 'msg'=>'添加成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'添加失败!'];
				}
			}else{
				$ret = Db::name('verificationcode')->update($data);
				if($ret !==false){
					return ['code'=>0, 'msg'=>'更新成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'添加失败!'];
				}
			}
			
			

		}else{
			die('非法访问!');
		}
	}

	public function pay(){
		if ( Request::instance()->isPost() ) {
			$oid= session('oid');
			//$path = '../extend/wxpay/cert/'.$oid.'/';
			$data = input('post.');
			/*if ($_FILES['sslcert_path']['name']) {
				$file = Request::instance()->file('sslcert_path');
				$file_info = $file->move($path,'');
				$file_info = $path.$file_info->getSaveName();
				$data['sslcert_path'] = $file_info;
			}
			//!empty($_FILES['file']['tmp_name'])
			if($_FILES['sslkey_path']['name']){
				$file1 = Request::instance()->file('sslkey_path');
				$file1_info = $file1->move($path,'');
				$file1_info = $path.$file1_info->getSaveName();
				$data['sslkey_path'] = 	$file1_info;
			}*/
			$id = (int)input('id');
			if(!$id){
				//$data2 = Request::instance()->only('mchid,mchkey,submerchant,sslcert_path,sslkey_path','post');
				$data2 = Request::instance()->only('mchid','post');
				$data2['oid'] = session('oid');	
				$data2['submerchant'] = 1;
				$ret = Db::name('wechatpay')->insert($data2);
				if($ret){
					return ['code'=>0, 'msg'=>'添加成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'添加失败!'];
				}
			}else{
				//var_dump($data);die;
				$ret = Db::name('wechatpay')->update($data);
				if($ret !==false){
					return ['code'=>0, 'msg'=>'更新成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'更新失败!'];
				}
			}
			//var_dump($data);die;

		}else{
			die('非法访问!');
		}
	}

	public function xy(){
		if ( Request::instance()->isPost() ) {
			$data = input('post.');
			$id = (int)input('id');
			if(!$id){
				$data2 = Request::instance()->only('xy1,xy2,xy3,xy4','post');
				$data2['oid'] = session('oid');	
				$ret = Db::name('agreement')->insert($data2);
				if($ret){
					return ['code'=>0, 'msg'=>'添加成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'添加失败!'];
				}
			}else{
				$ret = Db::name('agreement')->update($data);
				if($ret !==false ){
					return ['code'=>0, 'msg'=>'更新成功!!'];
				}else{
					return ['code'=>-1050, 'msg'=>'更新失败!'];
				}
			}
			
		}else{
			die('非法访问!');
		}

	}

	public function oedit(){
		if ( Request::instance()->isPost() ) {
			$data = input('post.');
			$id = (int)input('id');
			$did = (int)input('did');
			$ret = Db::name('operator_order')->where('id',$did)->find();//查询订单表中的订单号,然后校验一下是否已支付完成
			$orderNo = $ret['order_no'];
			$app = $this ->initialize();
			//var_dump($orderNo);die;
			if(!empty($orderNo)){
				$payment = $app->payment;
				$result = $payment->query($orderNo);
				//var_dump($result);die;
				if($result['trade_state']=='SUCCESS'){
					$data2 = array(
						'trade_no' => $result['transaction_id'],
						'pay_status' => 1,
						'pay_mode' => 1,
						'payment_date' => strtotime($result['time_end']),
						'id' => $did,
					);
					$num = Db::name('operator_order')->update($data2);
					if($num !==false){
						Db::name('operator')->where('id',$id)->setField('initialization',1);
						return ['code'=>0, 'msg'=>'/ausagent/Index/default'];
					}else{
						return ['code'=>-1050, 'msg'=>'支付失败!'];
					}
				}else{
					return ['code'=>-1050, 'msg'=>'你还没有支付!'];
				}
			}
			//var_dump($data);die;
		}else{
			die('非法访问!');
		}
	}
	public function edit(){
		if ( Request::instance()->isPost() ) {
			$id = (int)input('id');
			if($id){
				$ret = Db::name('operator')->where('id',$id)->setField('initialization',1);
				if($ret !== false){
					return ['code'=>0, 'msg'=>'/ausagent/Index/default'];
				}else{
					return ['code'=>-1050, 'msg'=>'更新失败!'];
				}
			}
		}else{
			die('非法操作!');
		}
	}

	public function onpay(){
		if ( Request::instance()->isPost() ) {
			$id = (int)input('id');
			$orders = Db::name('operator_order')->where('id',$id)->find();
			if(!$orders){
				return ['code'=>-1050, 'msg'=>'您的操作有误!!'];
			}
			//var_dump($orders);die;
			$orderno = $orders['order_no'];//订单号
			$detail = '曼联智能柜软件服务费用';
			$price = $orders['real_amount'];
			$ver = Db::name('version')->where('id',$orders['version'])->find();

			if($ver['free'] == 0){ //判断是否免费版本
				var_dump($orders);die;
				$notify_url = config('website').'/ausagent/Initialization/rechargenotify';
				$app = $this ->initialize();
	        	$payment = $app->payment;
	        	$attributes = [
		            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
		            'body'             => $detail,  //订单名称
		            'detail'           => $detail,  //订单描述
		            'out_trade_no'     => $orderno,  //订单号
		            'total_fee'        => $price*100, // 单位：分
		            'notify_url'       => $notify_url,
	        	];
	        	$order = new Order($attributes);
	        	$result = $payment->prepare($order);
	        	if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
	        		$prepayId = $result->prepay_id;
			            $url = $result->code_url;
			            $errorCorrectionLevel ='L';//容错级别
				        $matrixPointSize = intval(18);//生成图片大小
				        Loader::import('qrcode.phpqrcode');
				        //生成二维码图片
				        \QRcode::png($url, 'payqrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
				        $QR = 'payqrcode.png';//已经生成的原始二维码图 
				        $imgurl ='/payqrcode.png';
				        
				        return ['code'=>0, 'msg'=>$imgurl];
				        /*$this->assign('img',$imgurl);
				        return $this->fetch('jysetting/onpay');*/
	        	}else{
	        		return ['code'=>-1050, 'msg'=>$result];
	        	}
			}else{
				$odata['pay_status'] = 1;
				$odata['old_expiration_date'] = $orders['new_expiration_date'];
				$odata['new_expiration_date'] ='';
				$odata['payment_date'] = time();
				$oret = Db::name('operator_order')->where('id',$id)->update($odata);
				if($oret){
					$upoperator['version'] = $orders['version'];
					$upoperator['expiration_date'] = $orders['new_expiration_date'];
				Db::name('operator')->where('id',session('oid'))->update($upoperator);	
					return ['code'=>1, 'msg'=>'续费成功!'];
				}else{
					return ['code'=>-1050, 'msg'=>'续费失败!'];
				}
			}
			
			//var_dump($id);die;
		}else{
			die('非法操作!');
		}

	}

	public function check(){
		if ( Request::instance()->isPost() ) {
			$id = (int)input('id');
			$ret = Db::name('operator_order')->where('id',$id)->find();
			if($ret){
				$orderNo = $ret['order_no'];
				$app = $this ->initialize();
				$payment = $app->payment;
				$result = $payment->query($orderNo);
				if($result['trade_state']=='SUCCESS'){
					$data2 = array(
						'trade_no' => $result['transaction_id'],
						'pay_status' => 1,
						'pay_mode' => 1,
						'old_expiration_date' =>$ret['new_expiration_date'],
						'new_expiration_date' => 0,
						'payment_date' => strtotime($result['time_end']),
						'id' => $id,
					);
					Db::name('operator')->where('id',$ret['oid'])->setField('expiration_date', $ret['new_expiration_date']);
					$num = Db::name('operator_order')->update($data2);
					if($num !==false){
						//Db::name('operator')->where('id',$id)->setField('initialization',1);
						Db::name('operator')->where('id',session('oid'))->setField('version',$ret['version']);
						return ['code'=>0, 'msg'=>'支付成功'];
					}else{
						return ['code'=>-1050, 'msg'=>'支付失败!'];
					}
				}else{
					return ['code'=>-1050, 'msg'=>'你还没有支付!'];
				}
			}else{
				die('您的操作有误!');
			}
		}
	}

	public function addorder(){
		if ( Request::instance()->isPost() ) {
			$time = (int)input('endtime');
			$dq = (int)input('dq');
			if($time){
				$maturity =  strtotime("+".$time."month",$dq);
			}else{
				return ['code'=>-1050, 'msg'=>'请选择到期时长!'];
			}
			$info = Db::name('operator')
				  ->alias('a')
				  ->join('version b','a.version = b.id')
				  ->where('a.id',session('oid'))
				  ->field('b.price,b.id')
				  ->find();
			
			$data['payable_amount'] = $time * $info['price'];
 			$data['real_amount'] = $time * $info['price'];
			$data['order_no'] = '20' . date('ymdHis') . rand(1000, 9999);
			$data['pay_status'] = 2;
			$data['create_user'] = session("id");
			$data['create_time'] = time();
			$data['is_delete'] = 1;
			$data['new_expiration_date'] = $maturity;
			$data['oid'] = session('oid');
			$data['version'] = $info['id'];
			$data['old_expiration_date'] = input('dq');
			//var_dump($data);die;
			if(Db::name('operator_order')->insert($data)){
				$id = Db::name(Config::get('operator_order'))->getLastInsID();
				$orders = Db::name('operator_order')->where('id',$id)->find();
				if(!$orders){
					return ['code'=>-1050, 'msg'=>'您的操作有误!!'];
				}
				$orderno = $orders['order_no'];//订单号
				$detail = '曼联智能柜软件服务费用';
				$price = $orders['real_amount'];
				$notify_url = config('website').'/ausagent/Initialization/rechargenotify';
				$app = $this ->initialize();
	        	$payment = $app->payment;
	        	$attributes = [
		            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
		            'body'             => $detail,  //订单名称
		            'detail'           => $detail,  //订单描述
		            'out_trade_no'     => $orderno,  //订单号
		            'total_fee'        => $price*100, // 单位：分
		            'notify_url'       => $notify_url,
	        	];
	        	$order = new Order($attributes);
	        	$result = $payment->prepare($order);
	        	if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
	        		$prepayId = $result->prepay_id;
			            $url = $result->code_url;
			            $errorCorrectionLevel ='L';//容错级别
				        $matrixPointSize = intval(18);//生成图片大小
				        Loader::import('qrcode.phpqrcode');
				        //生成二维码图片
				        \QRcode::png($url, 'payqrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
				        $QR = 'payqrcode.png';//已经生成的原始二维码图 
				        $imgurl ='/payqrcode.png';
				        return ['code'=>0, 'msg'=>$imgurl,'id'=>$id];
	        	}else{
	        		return ['code'=>-1050, 'msg'=>$result];
	        	}
 			}else{
 				return ['code'=>-1050, 'msg'=>'续费失败！'];
 			}
		}
	}
	
	
}